package com.akkainaction.cluster.clusterstate;

import akka.actor.ActorSystem;
import akka.actor.Props;
import akka.actor.UntypedActor;
import akka.cluster.Cluster;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;

import java.util.concurrent.TimeUnit;

import static akka.cluster.ClusterEvent.*;

public class ClusterStateActor extends UntypedActor {

    Cluster cluster = Cluster.get(getContext().system());

    @Override
    public void preStart() {
        cluster.subscribe(getSelf(), initialStateAsEvents(), UnreachableMember.class, MemberEvent.class);
    }

    @Override
    public void postStop() throws Exception {
        cluster.unsubscribe(getSelf());
    }

    @Override
    public void onReceive(Object message) throws Exception {

    }

    public static void main(String[] args) throws InterruptedException {
        Config config = ConfigFactory.load("akka-cluster-state.conf");
        ActorSystem system = ActorSystem.create("sys", config);
        system.actorOf(Props.create(ClusterStateActor.class), "clusterStateNode");
        while (true){
            CurrentClusterState state= Cluster.get(system).state();
            TimeUnit.SECONDS.sleep(10);
            System.out.println("Leader节点:" + state.getLeader());
            System.out.println("所有节点列表:" + state.getMembers());
            System.out.println("unreachable节点列表:" + state.getUnreachable());
            System.out.println("#######################################################");
        }
    }

}
